package cn.laixueit;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.ObjectId;
import cn.hutool.core.util.HashUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.laixueit.base.R;
import cn.laixueit.controller.FileUplodaController;
import cn.laixueit.export.service.FileExportService;
import cn.laixueit.pojo.Book;
import cn.laixueit.pojo.DatadictionartDetail;
import cn.laixueit.pojo.Soft;
import cn.laixueit.service.BookService;
import cn.laixueit.service.CategoryService;
import cn.laixueit.service.DatadictionartService;
import cn.laixueit.service.SoftService;
import cn.laixueit.utils.CommonUtils;
import cn.laixueit.utils.ExportWordUtils;
import cn.laixueit.vo.BookVo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;

/**
 * @author duxiang
 * @date 2023/11/27 9:30
 */

@SpringBootTest
@RunWith(SpringRunner.class)
public class Demo {

    @Test
    public void t() {
        //加密工具
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        //加密配置
        EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
        //加密算法，写死即可
        config.setAlgorithm("PBEWithMD5AndDES");
        //加密使用salt设置
        config.setPassword("software");
        //应用配置
        encryptor.setConfig(config);
        //需要加密数据
        String plaintext = "123456";
        String plaintex2t = "root";
        //加密
        String encrypttext = encryptor.encrypt(plaintext);
        String e = encryptor.encrypt(plaintex2t);

        System.out.println(plaintext + " : " + encrypttext);
        System.out.println(e + " : " + e);
    }

    @Resource
    private SoftService softService;

    @Test
    public void t2() {
        softService.save(Soft.builder()
                .name("lisi")
                .build());
    }

    @Resource
    private BookService bookService;

    @Test
    public void t3() {
        Page<Book> bookPage = new Page<>(1, 10);
        BookVo vo = new BookVo();
        R r = bookService.listPage(bookPage, vo);
        System.out.println("r = " + r);
    }

    @Test
    public void t4() {
        bookService.saveOrUpdateBook(Book.builder()
                .name("java安装").descs("描述").discount(BigDecimal.TEN).downurl("www.baidu.com")
                .imageUrl("www.11").isHot(true).isPay(false).isShow(true).money(BigDecimal.TEN).sort(1)
                .build());
    }

    @Test
    public void t5() {
        BookVo vo = bookService.getRowAndChapter("1734864121242853377", null);
        System.out.println("vo = " + vo);
    }

    @Test
    public void t6() {
        Book vo = bookService.listBookAndChaptersAndContents("1734864121242853377");
        System.out.println("vo = " + vo);
    }

    @Resource
    private ExportWordUtils exportWordUtils;

    @Test
    public void t7() {
        LinkedList<Map<String, List>> wordText = exportWordUtils.createWordText(Arrays.asList("1734864121242853377"));
        System.out.println("wordText = " + wordText);
    }


    @Resource
    private FileExportService fileExportService;

    @Test
    public void t8() {
        fileExportService.downLoadWordList(Arrays.asList("1734864121242853377"), null);
    }

    @Test
    public void t9() {
        R r = bookService.listBookAndOneChapters(new BookVo());
        Object rows = r.get("rows");
        System.out.println("rows = " + rows);
    }

    @Test
    public void t10() {
        R r = bookService.chapterContent("1736623844971569154");
        System.out.println(r);
    }

    @Resource
    private DatadictionartService datadictionartService;

    @Test
    public void t11() {
        Map<String, LinkedList<DatadictionartDetail>> map = datadictionartService.getDataDictionArtMapList("");
        System.out.println(map);
    }

    @Resource
    private CommonUtils commonUtils;

    @Test
    public void t12() {
        for (int i = 0; i < 10; i++) {
            String s = commonUtils.randomName("xxx-ass");
            System.out.println("s = " + s);
        }
    }

    @Resource
    private FileUplodaController fileUplodaController;
    @Resource
    private HttpServletRequest request;

    @Test
    public void t13() throws IOException {
        File file = new File("D:\\软件下载地址.xlsx");
        MultipartFile mulFile = new MockMultipartFile(
                file.getName(), //文件名
                file.getName(), //originalName 相当于上传文件在客户机上的文件名,
                "text/plain",
                new FileInputStream(file) //文件流
        );
        R r = fileUplodaController.upload(null, mulFile);
        System.out.println(r);
    }

    @Resource
    private CategoryService categoryService;

    @Test
    public void t14() throws IOException {
        List<Map<String, Object>> mapList = categoryService.listTree(null);
        System.out.println(mapList);
    }

    @Test
    public void t15() throws IOException {
        categoryService.removeCategory(1);
    }


    @Test
    public void t16() throws IOException {
        LocalDate now = LocalDate.now();
        YearMonth yearMonth = YearMonth.from(now);
        String yearMonthStr = yearMonth.toString();
        System.out.println("yearMonthStr = " + yearMonthStr);
    }

    @Test
    public void t17() throws IOException {
        int c = HashUtil.javaDefaultHash("c");
        System.out.println(c);
    }

    @Test
    public void adjustTimeZone() throws ParseException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat();
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String s = format.format(date);
        Date parse = format.parse(s);
        System.out.println("s = " + parse);
    }

    @Test
    public void t18() throws ParseException {
        Soft build = Soft.builder()
                .name("xx")
                .isPay(true)
                .money(BigDecimal.TEN)
                .id("123")
                .build();
        LinkedHashMap<String, Object> map = convertMap(build,false, null, "name");
        System.out.println("map = " + map);
    }

    /**
     * 将对象转换成map，同时移除不需要的字段
     *
     * @param o        需要转换的对象
     * @param isResultAllField 是否需要所有字段返回，没有值返回null
     * @param isRetain 是否是保留字段 true 为保留，false为删除，null为不操作，直接返回转换后的map
     * @param cloKeys  需要操作的字段key （可选）
     * @return 操作转换后的map
     */

    public LinkedHashMap<String, Object> convertMap(Object o,Boolean isResultAllField, Boolean isRetain, String... cloKeys) {
        Field[] fields = ReflectUtil.getFields(o.getClass());
        String objJson = JSON.toJSONString(o);
        Map map = JSON.parseObject(objJson, Map.class);
        LinkedHashMap<String, Object> linkedHashMap = new LinkedHashMap<String, Object>(map);

        if(isResultAllField) {
            Set<String> keySet = linkedHashMap.keySet();
            for (Field field : fields) {
                String name = field.getName();
                Boolean b = keySet.stream().allMatch(x -> !StringUtils.equals(x, name));
                if (b) {
                    linkedHashMap.put(name, null);
                }
            }
        }
        if (ObjectUtil.isNull(isRetain)) {
            return linkedHashMap;
        }
        List<String> keys = Arrays.asList(cloKeys).stream().filter(StrUtil::isNotBlank).collect(Collectors.toList());
        if (isRetain) {
            LinkedHashMap<String, Object> hashMap = new LinkedHashMap<>();
            keys.stream().forEach(x -> {
                if (ObjectUtil.isNotEmpty(linkedHashMap.get(x))) {
                    hashMap.put(x, linkedHashMap.get(x));
                }
            });
            return hashMap;
        } else {
            if (CollectionUtil.isNotEmpty(keys)) {
                keys.stream().forEach(x -> linkedHashMap.remove(x));
            }
        }
        return linkedHashMap;
    }

    @Test
    public void t19() throws ParseException {
        for (int i = 0; i < 10; i++) {
            System.out.println(ObjectId.next());
        }
        System.out.println(DateUtil.format(LocalDateTime.now(), "yyyyMMdd"));
    }

    @Test
    public void t20() throws ParseException {
        int i = 10 | 22;
        System.out.println("i = " + i);
    }

    @Test
    public void t21() throws ParseException {
        ArrayList<String> list = new ArrayList<String>() {{
            add("a");
            add("b");
            add("c");
        }};
        ArrayList<String> list2 = new ArrayList<String>() {{
            add("1");
            add("2");
            add("3");
        }};
        List<ArrayList<String>> lists = Arrays.asList(list, list2);
        System.out.println(lists);
        List<String> collect = lists.stream().flatMap(ArrayList::stream).collect(Collectors.toList());
        System.out.println("collect = " + collect);
    }

    @Test
    public void t22() throws ParseException {
        List<Map<String, String>> date = createDate("yyyyMMdd");
        System.out.println(date);
    }

    /**
     * 根据传递的字符串格式进行日期格式化，如果不传递默认返回年的字符串“2024”
     *
     * @param dateFormat 日期格式（可选）
     * @return 返回日期格式的字符串数组
     * @throws RuntimeException 可能会抛出日期格式不正确的的处理异常，建议自行处理
     */
    public List<Map<String, String>> createDate(final String... dateFormat) {
        LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
        List<Map<String, String>> list = Arrays.asList(dateFormat).stream().distinct().filter(StringUtils::isNoneBlank).map(x -> {
            HashMap<String, String> map = new HashMap<>();
            map.put(x, DateUtil.format(now, x));
            return map;
        }).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(list)) {
            return list;
        } else {
            HashMap<String, String> map = new HashMap<>();
            map.put("y", Year.from(now).toString());
            map.put("ym", YearMonth.from(now).toString());
            map.put("ymd", DateUtil.format(now,"yyyyMMdd"));
            list.add(map);
            return list;
        }
    }


    @Test
    public void t23() throws ParseException {
        List<String> strings = Arrays.asList("1", "2", "3");
        List<Integer> list = strings.stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());
        System.out.println("list = " + list);
    }

    @Test
    public void t24() throws ParseException {
        Optional.ofNullable(1).ifPresent(x-> System.out.println("1"));
    }

    @Test
    public void t25(){
        R r = softService.softdetail("1730062540978802689");
        Object o = r.get("obj");
        System.out.println("o = " + o);
    }

    @Test
    public void t26(){
        LongStream.range(0,2).forEach(x-> System.out.println(x));
    }

    @Test
    public void t27(){
        boolean b = Optional.ofNullable(null).isPresent();
        System.out.println("b = " + b);
    }

    @Test
    public void t28(){
        // 创建两个集合
        Collection<String> collection1 = new ArrayList<>();
        collection1.add("A");

        Collection<String> collection2 = new ArrayList<>();
        collection2.add("A");
        collection2.add("B");
        collection2.add("C");

        List<String> collect = collection1.stream().filter(x -> {
            return collection2.stream().allMatch(y -> !StringUtils.equals(y, x));
        }).collect(Collectors.toList());
        System.out.println("collect = " + collect);

        List<String> collect2 = collection2.stream().filter(x -> {
            return collection1.stream().allMatch(y -> !StringUtils.equals(y, x));
        }).collect(Collectors.toList());
        System.out.println("collect2 = " + collect2);

        List<String> collect3 = collection1.stream().filter(x -> {
            return collection2.stream().allMatch(y -> StringUtils.equals(y, x));
        }).collect(Collectors.toList());
        System.out.println("collect3 = " + collect3);
    }

    @Test
    public void t29(){
        HashSet<Object> set = new HashSet<>();
        System.out.println("CollectionUtil.isEmpty(collection1) = " + CollectionUtil.isEmpty(set));
    }


    @Test
    public void t30(){
        // 创建两个集合
        Collection<String> collection1 = new ArrayList<>();
        collection1.add("B");

        Collection<String> collection2 = new ArrayList<>();
        collection2.add("A");
        collection2.add("B");
        collection2.add("C");

        List<String> collect2 = collection2.stream().filter(x -> {
            return collection1.stream().allMatch(y -> !StringUtils.equals(y, x));
        }).collect(Collectors.toList());
        System.out.println("collect2 = " + collect2);

    }

    @Test
    public void t31(){

        Collection<String> collection2 = new ArrayList<>();
        collection2.add("A");
        collection2.add("B");
        collection2.add("C");

        Optional.ofNullable(collection2).ifPresent(x->{
            System.out.println(x);
        });

    }

    @Test
    public void t33(){
        String ss = null;
        String s = Optional.ofNullable(ss).orElse("22");
        System.out.println("s = " + s);

    }


    @Test
    public void t34() throws UnsupportedEncodingException {
        String s = "%E4%BC%A0%E5%85%A5%E6%95%B0%E6%8D%AE%E5%92%8C%E6%95%B0%E6%8D%AE%E5%BA%93%E6%95%B0%E6%8D%AE%E8%BF%9B%E8%A1%8C%E5%B7%AE%E9%9B%86%E6%AF%94%E5%AF%B9";
        String s1 = URLDecoder.decode(s, "utf-8");
        System.out.println(s1);
        cn.hutool.core.net.URLDecoder.decode(s, Charset.defaultCharset());
    }
}
